# Replication Archive for: Aggarwal, Minali, Jennifer Allen, Alex Coppock, 
# Dan Frankowski, Sol Messing, Kelly Zhang, James Barnes, Andrew Beasley, 
# Harry Hantman, and Sylvan Zheng: The impact of digital campaign advertising 
# during the 2020 US presidential election: evidence from survey experiments, 
# field experiments, and a campaign-level experiment. 
# Nature Human Behavior, forthcoming.

rm(list = ls())
library(tidyverse)
library(estimatr)
library(scales)
library(xtable) 
source("helper_file.R")

# load data and uncount
aggregated_set <- read_rds(file = "aggregated_analysis_set.rds")
main_analysis_set <- uncount(aggregated_set, weights = n)


my_percent = percent_format(accuracy = 0.1)
my_comma = label_comma()

summary_table <-
  main_analysis_set %>%
  group_by(strata) %>%
  summarize(
    `Control` = my_comma(sum(condition == "control")),
    `Treatment` = my_comma(sum(condition == "treat")),
    `Assignment Probability` = format_num(mean(treatment_prob), 3),
    voting_rate_2020_control = 
      my_percent(mean(voted_in_2020[condition == "control"])),
    voting_rate_2020_treatment = 
      my_percent(mean(voted_in_2020[condition == "treat"]))
  )

summary_table <-
  summary_table %>% 
  separate(strata, into = c("Gender", "Race", "Age"), sep = "\\_") %>% 
  mutate(Gender = str_to_title(Gender),
         Race = str_to_title(Race),
         Age = str_to_title(Age))


summary_table_overall <-
  main_analysis_set %>%
  ungroup %>% 
  summarize(
    Gender = "",
    Race = "",
    Age = "Total",
    `Control` = my_comma(sum(condition == "control")),
    `Treatment` = my_comma(sum(condition == "treat")),
    `Assignment Probability` = format_num(mean(condition == "treat")),
    voting_rate_2020_control = 
      my_percent(weighted.mean(voted_in_2020[condition == "control"], w =ipw[condition == "control"])),
    voting_rate_2020_treatment = 
      my_percent(weighted.mean(voted_in_2020[condition == "treat"], w =ipw[condition == "treat"]))
  )



xtable(summary_table) %>% 
  print(include.colnames = FALSE,
        include.rownames = FALSE,
        only.contents = TRUE,
        hline.after = c(), file = "output/table_1a.tex")
xtable(summary_table_overall) %>% 
  print(include.colnames = FALSE,
        include.rownames = FALSE,
        only.contents = TRUE,
        hline.after = c(), file = "output/table_1b.tex")

